package com.tstudy.laoshibang.profile;


import org.androidannotations.annotations.AfterViews;
import org.androidannotations.annotations.Click;
import org.androidannotations.annotations.EFragment;
import org.androidannotations.annotations.ViewById;
import org.androidannotations.annotations.res.StringRes;
import org.apache.http.Header;

import com.loopj.android.http.ResponseHandlerInterface;
import com.tstudy.laoshibang.R;
import com.tstudy.laoshibang.base.BaseActivity;
import com.tstudy.laoshibang.base.BaseApplication;
import com.tstudy.laoshibang.base.CONSTANT;
import com.tstudy.laoshibang.base.HttpManager;
import com.tstudy.laoshibang.event.UpdateInfoEvent;
import com.tstudy.laoshibang.event.UpdateLoginStatusEvent;
import com.tstudy.laoshibang.login.NeedLoginFragment;
import com.tstudy.laoshibang.manager.UserManager;
import com.tstudy.laoshibang.mode.response.BaseResponse;
import com.tstudy.laoshibang.mode.response.UserResponse;

import android.os.Bundle;
import android.os.Handler;
import android.support.v4.app.Fragment;
import android.text.TextUtils;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnKeyListener;
import android.view.ViewGroup;
import android.widget.EditText;
import android.widget.TextView;
import de.greenrobot.event.EventBus;
@EFragment(R.layout.update_user)
public class UpdateUserFragment extends NeedLoginFragment implements OnKeyListener{
	private final static String TAG="update_user";
	@ViewById(R.id.update_user_root)
	View mRootLayout;
	
	@ViewById(R.id.update_user_confirm)
	TextView mConfirmTxt;
	@ViewById(R.id.update_user_new)
	EditText mInputExt;
	
	@ViewById(R.id.update_user_title)
	TextView mTitleTxt;
	

	@ViewById(R.id.update_user_desc)
	TextView mUpdateUserDesc;
	
	@StringRes(R.string.common_modify)
	String mTitlePreStr;
	String mKey;
	String mValue;
	String mTitle;
	Handler mHandler;
	boolean mIsFirstLoad = true;//判断是否是第一次加载
	
	public static void add(String name,String value,String title,int containerViewId){
		Bundle args = new Bundle();
		args.putInt(CONSTANT.ARGS.FRAGMENT_ID, containerViewId);
		args.putString(CONSTANT.ARGS.NAME, name);
		args.putString(CONSTANT.ARGS.VALUE, value);
		args.putString(CONSTANT.ARGS.TITLE, title);
		Fragment fragment = Fragment.instantiate(BaseApplication.mContext,UpdateUserFragment_.class.getName(), args);
		((BaseActivity) BaseApplication.mCurrentActivity).add(containerViewId,fragment,TAG);
	}
	
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		mHandler = new Handler();
	}
	
	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,Bundle savedInstanceState) {
		mIsFirstLoad = mRootLayout == null;
		if (mRootLayout != null) {
			((ViewGroup)mRootLayout.getParent()).removeAllViews();
		}
		return mRootLayout;
	}
	
	@AfterViews
	public void initView(){
		if (mIsFirstLoad) {
			mInputExt.setText(mValue);
			mTitleTxt.setText(mTitlePreStr + mTitle);
//			if (mNameStr.equals(mTitle)) {
//				mUpdateUserDesc.setText(R.string.user_update_name_desc);
//			}else if(mNickStr.equals(mTitle)){
//				mUpdateUserDesc.setText(R.string.user_update_nick_desc);
//			}
		}
	}
	
	@Click({R.id.update_user_confirm,R.id.update_user_back})
	public void clickAction(View v){
		switch (v.getId()) {
		case R.id.update_user_back:
			backAction(mFragmentId);
			break;
		case R.id.update_user_confirm:
			if (TextUtils.isEmpty(mInputExt.getText())) {
				BaseApplication.showToast(mTitle + "不能为空");
				return;
			}
			if(mInputExt.getText().toString().length() > 15) {
				BaseApplication.showToast(R.string.common_save_error);
				return;
			}
			updateUserInfo(mKey,mInputExt.getText().toString(),CONSTANT.UPDATE_TYPE_STRING);
			break;
		default:
			break;
		}
		showSoftKeyBoard(mInputExt,false);
	}
	
	public void updateUserInfo(String key,String value,int type){
		ResponseHandlerInterface response = new BaseJsonHandler<BaseResponse>() {
			@Override
			public void onSuccess(int statusCode, Header[] headers,
					String rawJsonResponse, BaseResponse response) {
				super.onSuccess(statusCode, headers, rawJsonResponse, response);
				if (response != null && response.getErr() == CONSTANT.NO_ERROR_STATUS) {
					getUserInfo();
					BaseApplication.showToast(R.string.common_save_success);
				} else {
                    BaseApplication.showToast(R.string.common_save_error);
                }
			}
			@Override
			protected BaseResponse parseResponse(String rawJsonData, boolean isFailure)
					throws Throwable {
				return mGson.fromJson(rawJsonData,BaseResponse.class);
			}
		};
		HttpManager.getInstance().updateUserInfo(BaseApplication.mUserNo, key, value,type,response);
	}
	
	/**
	 * 获取用户资料
	 */
	public void getUserInfo(){
		ResponseHandlerInterface response = new BaseJsonHandler<UserResponse>() {
			@Override
			public void onSuccess(int statusCode, Header[] headers,
					String rawJsonResponse, UserResponse response) {
				super.onSuccess(statusCode, headers, rawJsonResponse, response);
				if (response != null && response.getErr() == CONSTANT.NO_ERROR_STATUS) {
					BaseApplication.mCurrentUser = response.getData();
					BaseApplication.mCurrentUser.allDicStr();
					BaseApplication.mCurrentUser.isLogin = 1;
					UserManager.getInstance().insertOrUpdate(BaseApplication.mCurrentUser);
					EventBus.getDefault().post(new UpdateInfoEvent());
					EventBus.getDefault().post(new UpdateLoginStatusEvent());
					backAction(mFragmentId);
				} else {
                    BaseApplication.showToast(response.getErrMsg());
                }
			}
			@Override
			protected UserResponse parseResponse(String rawJsonData, boolean isFailure)
					throws Throwable {
				return mGson.fromJson(rawJsonData,UserResponse.class);
			}
		};
		HttpManager.getInstance().getUserInfo(BaseApplication.mUserNo, response);
	}
	
	@Override
	public void clear() {
		showSoftKeyBoard(mInputExt, false);
		mRootLayout = null;
		
	}
	@Override
	public void initArgs(Bundle args) {
		if (args != null) {
			mFragmentId = args.getInt(CONSTANT.ARGS.FRAGMENT_ID);
			mKey = args.getString(CONSTANT.ARGS.NAME);
			mValue = args.getString(CONSTANT.ARGS.VALUE);
			mTitle = args.getString(CONSTANT.ARGS.TITLE);
		}
	}

	@Override
	public boolean onKey(View v, int keyCode, KeyEvent event) {
		return false;
	}
	
}
